//
//  MemorandumViewController.swift
//  mggz
//
//  Created by QinWei on 2018/4/9.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import YYText
class MemorandumViewController: UIViewController {
    fileprivate lazy var textView:UITextView = {
        let textView = UITextView.init()
        
        return textView
    }()
    var isHaveEditing:Bool?
    
    //var passData:(([String:String]) -> Void)?
    fileprivate var textCount:Int?
    var currentProject: ProjectModel?
    var selectDate: Date?
    fileprivate lazy var saveButton:UIButton = {
        let button = UIButton(type: UIButtonType.system)
        button.setTitle("保存", for: .normal)
        button.backgroundColor = UIColor(red: 0.06, green: 0.56, blue: 0.91, alpha: 1)
        button.setTitleColor(UIColor.white, for: .normal)
        button.addTarget(self, action: #selector(saveData), for: .touchUpInside)
        return button
    }()
    
    fileprivate lazy var leftView : UIView = {
        let view = UIView.init()
        view.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
        let iconView = UIImageView.init()
        iconView.frame = CGRect(x: -10, y: 0, width: 20, height: 28)
        iconView.image = UIImage.init(named: "navigationButtonReturn")
        view.addSubview(iconView)
        let label = UILabel.init()
        label.text = "返回"
        label.font = UIFont.systemFont(ofSize: 17)
        label.frame = CGRect(x: 10, y: 3, width: 40, height: 21)
        view.addSubview(label)
        return view
    }()
    
    fileprivate lazy var textNum:UILabel = {
        let textNum = UILabel()
        textNum.text = "0/200"
        textNum.font = UIFont.systemFont(ofSize: 15)
        textNum.textColor = UIColor.lightGray
        textNum.textAlignment = .right
        return textNum
    }()
    fileprivate lazy var topView:UIView = {
        let view = UIView.init()
        return view
    }()
    fileprivate lazy var bottomView:UIView = {
        let view = UIView.init()
        return view
    }()
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "记事"
        self.isHaveEditing = false
        self.checkTheData()
        bottomView.backgroundColor = UIColor.mg_backgroundGray
        self.view.addSubview(bottomView)
        bottomView.snp.makeConstraints { (make) in
            make.top.equalTo(self.view).offset(41)
            make.right.left.bottom.equalTo(self.view)
        }
        
        self.leftView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(popPreviousPage))
        self.leftView.addGestureRecognizer(tap)
        
        let leftBtn = UIBarButtonItem(customView: self.leftView)
        self.navigationItem.leftBarButtonItem = leftBtn
        
        self.view.backgroundColor = UIColor.white
        bottomView.addSubview(topView)
        topView.snp.makeConstraints { (make) in
            make.top.equalTo(self.bottomView).offset(20)
            make.left.right.equalTo(self.view)
            make.height.equalTo(220)
        }
       // topView.backgroundColor = UIColor(white: 0.96, alpha: 1)
        self.topView.addSubview(self.textView)
        self.textView.snp.makeConstraints { (make) in
            make.top.equalTo(topView).offset(20)
            make.left.equalTo(topView).offset(20)
            make.right.equalTo(topView).offset(-20)
            make.bottom.equalTo(topView).offset(-20)
        }
        self.textView.delegate = self
        self.textView.layer.borderWidth = 1
        self.textView.layer.borderColor = UIColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1).cgColor
        self.textView.layer.cornerRadius = 5
        self.textView.layer.masksToBounds = true
        
        self.view.addSubview(saveButton)
        saveButton.snp.makeConstraints { (make) in
        make.top.equalTo(self.topView.snp.bottom).offset(30)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 200, height: 40))
        }
        self.view.addSubview(textNum)
        textNum.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(155)
            make.right.equalTo(self.view).offset(-30)
            make.size.equalTo(CGSize(width: 100, height: 21))
        }
        self.view.bringSubview(toFront: textNum)
    }
    
    @objc fileprivate func popPreviousPage(){
        if self.isHaveEditing == true {
            let alert = UIAlertController(title: "是否保存记事", message: "", preferredStyle: .alert)
            let refuseApp = UIAlertAction(title: "暂不", style: .cancel, handler: { (action) in
        self.navigationController?.popViewController(animated: true)
                
            })
            refuseApp .setValue(UIColor.lightGray, forKey: "titleTextColor")
            
            let gotoAppstore = UIAlertAction(title: "保存", style: .default, handler: { (action) in
                self.putDataSaved(completionHandler: { (response) in
                    
                    if response{
                    self.navigationController?.popViewController(animated: true)
                    }
                })
            })
            
            alert.addAction(gotoAppstore)
            alert.addAction(refuseApp)
            self.present(alert, animated: true, completion: {
                
            })
        }else{
        self.navigationController?.popViewController(animated: true)
            
        }
    }
    
    fileprivate func checkTheData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard (self.selectDate != nil) else {
            return
        }
        let signedDay : String = dateToString(date: self.selectDate!)
        guard let migrantWorkerID = self.currentProject?.migrantWorkerId  else {
            return
        }
       
    LCAPiSubManager.request(.GetMigrantWorkerSignedRemark(migrantWorkerID: migrantWorkerID, signedDay: signedDay, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                let result = jsonString["Result"] as? String
                self.saveButton.isEnabled = false
                self.saveButton.backgroundColor = UIColor.lightGray
                self.textView.text = result
                self.textCount = self.textView.text.count
                self.textNum.text =  "(\(self.textCount ?? 0)/\(200))"
                
            }
        }
}
    @objc fileprivate func saveData(){
        
        self.putDataSaved { (reponse) in
            
        }
    }
    fileprivate func putDataSaved(completionHandler:@escaping (Bool) -> Void){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard (self.selectDate != nil) else {
            return
        }
        let signedDay : String = dateToString(date: self.selectDate!)
        guard let migrantWorkerID = self.currentProject?.migrantWorkerId  else {
            return
        }
        guard (self.textView.text) != nil else{
            
            return
        }
        LCAPiSubManager.request(.SetMigrantWorkerSignedRemark(migrantWorkerID: migrantWorkerID, signedDay: signedDay, AccountId: accountId, remark: self.textView.text)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                
                guard (jsonString["State"]) as! String == "OK" else{
                    completionHandler(false)
                    return
                }
                
                self.saveButton.isEnabled = false
                self.saveButton.backgroundColor = UIColor.lightGray
                self.isHaveEditing = false
                completionHandler(true)
                WWSuccess("保存成功!")
            }
        }
    }
}
extension MemorandumViewController:UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        self.saveButton.isEnabled = true
        self.saveButton.backgroundColor = UIColor(red: 0.06, green: 0.56, blue: 0.91, alpha: 1)
        if textView.text.count > 150 {
            
            //获得已输出字数与正输入字母数
            let selectRange = textView.markedTextRange
            
            //获取高亮部分 － 如果有联想词则解包成功
            if let selectRange = selectRange {
                let position =  textView.position(from: (selectRange.start), offset: 0)
                if (position != nil) {
                    return
                }
            }
            
            let textContent = textView.text
            let textNum = textContent?.count
            
            //截取200个字
            if textNum! > 200 {
                let index = textContent?.index((textContent?.startIndex)!, offsetBy: 200)
                let str = textContent?.substring(to: index!)
                textView.text = str
            }
        }
        self.textCount = textView.text.count
        self.textNum.text =  "(\(self.textCount ?? 0)/\(200))"
        self.isHaveEditing = true
    }
}












